<template>
	<view>
		<u-popup :show="show" @close="close" @open="open" closeable>
			<view class="signature-page" v-if="type == 0">
				<!-- 顶部标题 -->
				<view class="page-header">
					<text class="title">电子签名</text>
					<text class="subtitle">请在下方区域签署您的姓名</text>
				</view>

				<!-- 签名组件 :upload-url="uploadUrl" :upload-config="uploadConfig" -->
				<view class="signature-wrapper">
					<signature-component ref="signatureRef" :min-speed="1.2" :min-width="2" :max-width="12"
						:open-smooth="true" :max-history-length="25" :bg-color="'#ffffff'"
						@complete="onSignatureComplete" @error="onSignatureError"></signature-component>
				</view>

				<!-- 操作按钮组 -->
				<view class="action-buttons">
					<view class="btn-row">
						<button class="btn btn-primary" @tap="handleSave">
							<text class="btn-icon">💾</text>
							<text class="btn-text">保存到相册</text>
						</button>

						<button class="btn btn-secondary" @tap="handlePreview">
							<text class="btn-icon">👁️</text>
							<text class="btn-text">预览签名</text>
						</button>
					</view>

					<view class="btn-row">
						<button class="btn btn-warning" @tap="handleClear">
							<text class="btn-icon">🗑️</text>
							<text class="btn-text">清空画布</text>
						</button>

						<button class="btn btn-info" @tap="handleUndo">
							<text class="btn-icon">↩️</text>
							<text class="btn-text">撤销上一步</text>
						</button>
					</view>

					<button class="btn btn-success confirm-btn" @tap="handleComplete">
						<text class="btn-icon">✅</text>
						<text class="btn-text">确认并上传签名</text>
					</button>
				</view>

				<!-- 预览区域 -->
				<view class="preview-section" v-if="previewImage">
					<view class="section-title">
						<text>签名预览</text>
					</view>
					<view class="preview-image-container">
						<image :src="previewImage" mode="aspectFit" class="preview-image" />
					</view>
				</view>

				<!-- 上传结果 -->
				<view class="result-section" v-if="uploadResult">
					<view class="section-title">
						<text>上传结果</text>
					</view>
					<view class="result-content">
						<text>{{ uploadResult }}</text>
					</view>
				</view>

				<!-- 状态提示 -->
				<view class="status-toast" v-if="statusMessage">
					<text>{{ statusMessage }}</text>
				</view>
			</view>
		</u-popup>

		<web-view :src="url"></web-view>
		<u-tabbar :fixed="true" :placeholder="true" :border="false">
			<view class="tabbar-item">
				<u-button text="取消" color="#ff707b"></u-button>
				<u-button v-if="type == 0" text="立即签署" color="linear-gradient(to right, #FF4856, #FF6F1C)"
					@click="show = true"></u-button>
				<u-button v-if="type == 1" text="下载合同" color="linear-gradient(to right, #FF4856, #FF6F1C)"></u-button>
			</view>
		</u-tabbar>
	</view>
</template>

<script>
import { apiGetContractSignList, apiGetContractUnsignList } from '@/request/api'
// 导入签名组件
import signatureComponent from '../sign/index.vue'
export default {
	components: {
		signatureComponent
	},
	data() {
		return {
			show: false,
			url: '',
			type: null,
			// 上传配置 - 根据实际API调整
			uploadUrl: 'https://your-api-domain.com/api/upload/signature',
			uploadConfig: {
				headers: {
					'Authorization': 'Bearer ' + uni.getStorageSync('token'),
					'X-Requested-With': 'XMLHttpRequest'
				},
				formData: {
					userId: uni.getStorageSync('userId') || 'unknown',
					businessType: 'contract',
					timestamp: Date.now(),
					platform: uni.getSystemInfoSync().platform
				},
				fileName: `signature_${Date.now()}`,
				fileType: 'png',
				quality: 0.9,
				timeout: 20000,
				retryCount: 3
			},
			previewImage: '',
			uploadResult: '',
			statusMessage: '',
			signatureData: null
		};
	},
	onLoad(params) {
		let { type } = params
		this.type = type
		console.log(type, 'TYPE')
		// 直接加载本地的 pdf.html，它会自动加载 test.pdf  是链接的话可以跳转携带参数
		this.url = `/static/pdf.html`

		// // 可以从页面参数中获取业务信息
		// if (options.contractId) {
		// 	this.uploadConfig.formData.contractId = options.contractId
		// }

		this.showTips('请在画布区域签署您的姓名')

	},
	methods: {
		open() {
			// console.log('open');
		},
		close() {
			this.show = false
			// console.log('close');
		},
		async getContractSignList() {
			const res = await apiGetContractSignList({})
		},
		async getContractUnsignList() {
			const res = await apiGetContractUnsignList({})
		},
		// 显示提示信息
		showTips(message, duration = 3000) {
			this.statusMessage = message
			setTimeout(() => {
				this.statusMessage = ''
			}, duration)
		},

		// 保存签名
		handleSave() {
			if (!this.$refs.signatureRef) {
				this.showTips('签名组件未初始化')
				return
			}

			if (this.$refs.signatureRef.isEmpty()) {
				uni.showToast({
					title: '请先进行签名',
					icon: 'none',
					duration: 2000
				})
				return
			}

			this.$refs.signatureRef.saveCanvasAsImg()
			this.showTips('正在保存签名...')
		},

		// 预览签名
		handlePreview() {
			if (!this.$refs.signatureRef) {
				this.showTips('签名组件未初始化')
				return
			}

			if (this.$refs.signatureRef.isEmpty()) {
				uni.showToast({
					title: '请先进行签名',
					icon: 'none',
					duration: 2000
				})
				return
			}

			this.$refs.signatureRef.previewCanvasImg()
		},

		// 清空画布
		handleClear() {
			if (!this.$refs.signatureRef) {
				this.showTips('签名组件未初始化')
				return
			}

			uni.showModal({
				title: '提示',
				content: '确定要清空画布吗？',
				success: (res) => {
					if (res.confirm) {
						this.$refs.signatureRef.clear()
						this.previewImage = ''
						this.uploadResult = ''
						this.showTips('画布已清空')
					}
				}
			})
		},

		// 撤销操作
		handleUndo() {
			if (!this.$refs.signatureRef) {
				this.showTips('签名组件未初始化')
				return
			}

			this.$refs.signatureRef.undo()
		},

		// 完成并上传
		handleComplete() {
			if (!this.$refs.signatureRef) {
				this.showTips('签名组件未初始化')
				return
			}

			if (this.$refs.signatureRef.isEmpty()) {
				uni.showToast({
					title: '请先进行签名',
					icon: 'none',
					duration: 2000
				})
				return
			}

			uni.showModal({
				title: '确认签名',
				content: '确认提交此签名吗？提交后无法修改',
				success: (res) => {
					if (res.confirm) {
						this.$refs.signatureRef.complete()
						this.showTips('正在上传签名...', 5000)
					}
				}
			})
		},

		// 签名完成回调
		onSignatureComplete(result) {
			console.log('签名完成回调:', result)

			if (result.success) {
				this.signatureData = result
				this.previewImage = result.filePath
				this.uploadResult = `✅ 签名上传成功！\n\n` +
					`📁 文件已保存\n` +
					`⏰ 时间: ${new Date().toLocaleString()}\n` +
					`🆔 业务ID: ${this.uploadConfig.formData.contractId || '无'}`

				this.showTips('签名上传成功！')

				// 在实际业务中，这里可以跳转到下一步
				uni.showToast({
					title: '签名成功',
					icon: 'success',
					duration: 2000
				})

				// 3秒后返回上一页（根据业务需求调整）
				setTimeout(() => {
					uni.navigateBack({
						delta: 1,
						animationType: 'pop-out',
						animationDuration: 300
					})
				}, 3000)
			} else {
				this.uploadResult = `❌ 上传失败！\n\n` +
					`📛 错误: ${result.error || '未知错误'}\n` +
					`🔄 重试次数: ${result.retryCount || 0}`

				this.showTips('上传失败，请重试')

				uni.showModal({
					title: '上传失败',
					content: result.error || '网络异常，请检查网络后重试',
					showCancel: true,
					cancelText: '取消',
					confirmText: '重试',
					success: (res) => {
						if (res.confirm) {
							this.handleComplete()
						}
					}
				})
			}
		},

		// 错误处理
		onSignatureError(error) {
			console.error('签名组件错误:', error)
			uni.showToast({
				title: '发生错误，请重试',
				icon: 'error',
				duration: 2000
			})
		}

	}

}	 
</script>

<style scoped>
.tabbar-item {
	display: flex;
	justify-content: space-between;
	width: 100%;
	margin: 0 auto;
	gap: 20rpx;
}

.u-tabbar__content {
	height: 100px !important;
}

.u-button {
	width: 158px;
}


.signature-page {
	padding: 20rpx;
	background: #f8f9fa;
	height: 100vh;
}

.page-header {
	text-align: center;
	padding: 30rpx 0;

	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		display: block;
	}

	.subtitle {
		font-size: 28rpx;
		color: #666;
		margin-top: 10rpx;
		display: block;
	}
}

.signature-wrapper {
	background: #fff;
	border-radius: 16rpx;
	padding: 20rpx;
	margin: 20rpx 0;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.action-buttons {
	margin: 40rpx 0;
}

.btn-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 20rpx;
	gap: 20rpx;
}

.btn {
	flex: 1;
	padding: 24rpx 0;
	border-radius: 12rpx;
	border: none;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;

	&-primary {
		background: linear-gradient(135deg, #007aff, #0056cc);
		color: white;
	}

	&-secondary {
		background: linear-gradient(135deg, #ff9500, #ff6b00);
		color: white;
	}

	&-warning {
		background: linear-gradient(135deg, #ff3b30, #d70015);
		color: white;
	}

	&-info {
		background: linear-gradient(135deg, #5ac8fa, #007aff);
		color: white;
	}

	&-success {
		background: linear-gradient(135deg, #34c759, #00a651);
		color: white;
	}
}

.confirm-btn {
	width: 100%;
	margin-top: 30rpx;
}

.preview-section,
.result-section {
	background: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin: 30rpx 0;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	border-left: 8rpx solid #007aff;
	padding-left: 20rpx;
}

.preview-image-container {
	width: 100%;
	height: 300rpx;
	border: 2rpx dashed #ddd;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f9f9f9;
}

.preview-image {
	width: 100%;
	height: 100%;
	border-radius: 8rpx;
}

.result-content {
	background: #f8f9fa;
	padding: 24rpx;
	border-radius: 12rpx;
	font-size: 26rpx;
	line-height: 1.6;
	color: #333;
	white-space: pre-line;
}

.status-toast {
	position: fixed;
	bottom: 100rpx;
	left: 50%;
	transform: translateX(-50%);
	background: rgba(0, 0, 0, 0.7);
	color: white;
	padding: 20rpx 40rpx;
	border-radius: 50rpx;
	font-size: 26rpx;
	z-index: 1000;
	animation: fadeInOut 3s ease-in-out;
}

@keyframes fadeInOut {

	0%,
	100% {
		opacity: 0;
		transform: translateX(-50%) translateY(20rpx);
	}

	10%,
	90% {
		opacity: 1;
		transform: translateX(-50%) translateY(0);
	}
}

/* 响应式设计 */
@media (max-width: 768px) {
	.btn-row {
		flex-direction: column;
		gap: 15rpx;
	}

	.btn {
		width: 100%;
	}
}
</style>
